03 / 05

How would you efficiently remove an element from a slice while preserving order vs without preserving order?

Order-preserving removal is O(n) using append to shift elements. Order-non-preserving removal is O(1) by swapping the target with the last element and truncating.

Two removal strategies
When to choose each approach
  1. 1

    Use order-preserving for user-visible lists, queues, ordered results

  2. 2

    Use O(1) swap for internal buffers, worker job queues, sets where order is irrelevant

  3. 3

    For very frequent removals from large slices, consider a linked list instead

  4. 4

    Be careful with the shared-array problem: removeOrdered mutates the original backing array

  5. 5

    Go 1.21 slices package provides slices.Delete() for order-preserving removal